from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.core import serializers
import json
# Create your views here.
from .models import *


def tables(request):
    return render(request, 'tablesapp/tables.html', locals())


def tables_all(request):
    if request.method == 'GET':
        data = {}
        pub_code_type = serializers.serialize("json", Book.objects.all())
        data["data"] = json.loads(pub_code_type)
        return JsonResponse(data, safe=False)


# fields[name]=23123&fields[author]=123123&fields[times]=131&fields[publish]=3123&fields[ISBN]=313
def tables_add(request):
    if request.method == 'POST':
        count = Book.objects.all().count()
        name = request.POST.get("fields[name]")
        author = request.POST.get("fields[author]")
        publish = request.POST.get("fields[publish]")
        times = request.POST.get("fields[times]")
        ISBN = request.POST.get("fields[ISBN]")

        book = Book(id=count + 1, name=name, author=author, publish=publish, times=times, ISBN=ISBN)
        book.save()
        return HttpResponse(count + 1)


def tables_edit(request):
    if request.method == 'POST':
        pk = request.POST.get("pk")
        name = request.POST.get("fields[name]")
        author = request.POST.get("fields[author]")
        publish = request.POST.get("fields[publish]")
        times = request.POST.get("fields[times]")
        ISBN = request.POST.get("fields[ISBN]")
        book = Book.objects.get(id=pk)
        book.name = name
        book.author = author
        book.publish = publish
        book.times = times
        book.ISBN = ISBN
        book.save()
        return HttpResponse(pk)


def tables_delete(request):
    if request.method == "POST":
        pk = request.POST.get("pk")
        delrest = Book.objects.get(id=pk).delete()
        return HttpResponse(delrest)
